chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if (message.action === "getHierarchyInfo") {
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        function: getHierarchyInfoScript
      }, function(results) {
        if (chrome.runtime.lastError) {
          sendResponse({ success: false, error: chrome.runtime.lastError.message });
        } else {
          sendResponse({ success: true, data: results[0] });
        }
      });
    });
    return true; // 保持消息通道打开，以便异步响应
  }
});

function getHierarchyInfoScript() {
  let elements = document.querySelectorAll('*');
  let hierarchyData = [];
  console.log(elements);

  elements.forEach(element => {
    hierarchyData.push({
      tagName: element.tagName,
      id: element.id,
      classList: Array.from(element.classList)
    });
  });

  return hierarchyData;
}
